package com.xindaoapp.happypet.activity;

import java.io.File;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.media.MediaRecorder.AudioSource;
import android.media.MediaRecorder.VideoSource;
import android.os.Bundle;
import android.os.Environment;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Chronometer;
import android.widget.Chronometer.OnChronometerTickListener;
import android.widget.Toast;

import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.MoccaPreferences;

public class RecordActivity extends UMBaseActivity implements Callback {
    private int COUNTDOWN = 12;
    /** 最小录制时间 */
    private final int minRecordTime = 8;

    private SurfaceHolder holder;
    /** 定时器 */
    private Chronometer mChronometerTimer;
    /** 下一步 */
    private View mNextStepView;
    private View mCancelView;
    private View mRecordView;

    private Camera camera;
    private MediaRecorder mMediaRecorder;

    private String mVideoPath;
    private boolean isRecording;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_record);

        mVideoPath =
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/happypet/video/"
                        + System.currentTimeMillis() + ".mp4";

        File file =
                new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/happypet/video");
        if (!file.exists()) {
            file.mkdir();
        }

        mChronometerTimer = (Chronometer) findViewById(R.id.timer);
        mChronometerTimer.setBase(COUNTDOWN);
        mChronometerTimer.setText(String.format("00：00：%02d", COUNTDOWN));
        mChronometerTimer.setOnChronometerTickListener(new OnChronometerTickListener() {

            @Override
            public void onChronometerTick(Chronometer chronometer) {
                if (COUNTDOWN < 0) {
                    stop();
                    startVideoPreview();
                    return;
                }
                if (COUNTDOWN == minRecordTime) {
                    mNextStepView.setVisibility(View.VISIBLE);
                }
                mChronometerTimer.setText(String.format("00：00：%02d", COUNTDOWN--));
            }
        });

        SurfaceView mSurfaceView = (SurfaceView) findViewById(R.id.surfaceview);
        holder = mSurfaceView.getHolder();
        // 设置数据来源自外部.
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        holder.addCallback(this);

        mNextStepView = findViewById(R.id.next);
        mCancelView = findViewById(R.id.cancel);
        mRecordView = findViewById(R.id.record);
        mNextStepView.setOnClickListener(mOnClickListener);
        mCancelView.setOnClickListener(mOnClickListener);
        mRecordView.setOnClickListener(mOnClickListener);

        if (MoccaPreferences.IsShowDialogHint.get()) {
            new AlertDialog.Builder(this).setTitle("提示").setMessage("暂不支持竖屏录制，请横屏录制！")
                    .setNegativeButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).setPositiveButton("不再提醒", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            MoccaPreferences.IsShowDialogHint.put(false);
                        }
                    }).show();
        }


        // Toast.makeText(getBaseContext(), "暂不支持竖屏录制，请切换横屏录制！", Toast.LENGTH_SHORT).show();
    }

    private final OnClickListener mOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.record:
                    if (!isRecording) {
                        isRecording = true;
                        mChronometerTimer.start();
                        start();
                    } else {
                        if (COUNTDOWN > minRecordTime) {
                            Toast.makeText(getBaseContext(), "录制时间太短！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        stop();
                        startVideoPreview();
                    }
                    break;
                case R.id.next:
                    stop();
                    startVideoPreview();
                    break;
                case R.id.cancel:
                    stop();
                    // mChronometerTimer.stop();
                    finish();
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        camera = Camera.open();
        try {
            // 设置预览显示为holder
            camera.setPreviewDisplay(holder);
            camera.startPreview(); // 开始预览
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        camera.stopPreview(); // 停止预览
        camera.release(); // 释放摄像头
        // camera = null;
        // mMediaRecorder.release();
        // mMediaRecorder = null;
    }

    /**
     * 录制视频, 必须按照配置的步骤来设置.
     * 
     * @param v
     */
    @SuppressLint("InlinedApi")
    public void start() {
        // 开始录制视频

        // 1. 先停止预览, 再解锁摄像头
        camera.stopPreview();
        camera.unlock(); // 解锁摄像头

        mMediaRecorder = new MediaRecorder();

        // // 3. 设置摄像头
        mMediaRecorder.setCamera(camera); // 设置摄像头给媒体录制对象

        // // 4. 设置音频, 视频源来自哪里
        mMediaRecorder.setAudioSource(AudioSource.CAMCORDER);
        mMediaRecorder.setVideoSource(VideoSource.CAMERA);
        // 5. 设置输出格式和编码
        CamcorderProfile proFile = CamcorderProfile.get(CamcorderProfile.QUALITY_480P); // 得到一个480p的录制参数
        mMediaRecorder.setProfile(proFile);

        // 6. 设置输出文件
        mMediaRecorder.setOutputFile(mVideoPath);

        // 7. 给MediaRecorder设置录制视频时的预览界面
        mMediaRecorder.setPreviewDisplay(holder.getSurface());

        // 8. 准备开始录制
        try {
            mMediaRecorder.prepare();
            mMediaRecorder.start(); // 开始录制
        } catch (Exception e) {
            e.printStackTrace();
        }
        mRecordView.setSelected(true);
    }

    /**
     * 启动视频预览窗口
     */
    private void startVideoPreview() {
        Intent intent = new Intent(this, VideoPreviewActivity.class);
        intent.putExtra(Constants.PARAM_VIDEO_PATH, mVideoPath);
        startActivity(intent);
        finish();
    }

    /**
     * 停止录制视频
     * 
     * @param v
     */
    public void stop() {
        if (null != mMediaRecorder) {
            mMediaRecorder.stop(); // 停止录制
            mMediaRecorder.reset();
            mMediaRecorder.release();
        }

        // camera.release();
        // camera.lock(); // 锁上摄像头

        mChronometerTimer.stop();
        mChronometerTimer.setText(String.format("00：00：%02d", 0));

        // 开始预览界面
        // camera.startPreview();
    }
}
